package helixoide.secondlife.devices;


import helixoide.Util;
import helixoide.hxLog;
import java.util.ArrayList;

public class deviceHandlerThread implements Runnable
{
	private deviceManager theManagment;
	private String incoming;
	private boolean interrupted;
	public deviceHandlerThread(deviceManager theManagment, String incoming)
	{
		this.theManagment = theManagment;
		this.incoming = incoming.trim();
		interrupted = false;
	}
	public void run() 
	{
		if(incoming==null || incoming.equals(""))
		{
			this.interrupted = true;
		}
		try
		{
			if(Thread.interrupted())
			{
				hxLog.write("deviceHandlerThread","Thread interrupted");
				throw new InterruptedException();
				
			}
		}
		catch(InterruptedException e)
		{
			e.printStackTrace();
			hxLog.write("deviceHandlerThread",e.toString());
			interrupted = true;
		}
		if(interrupted==false)
		{
			
			String[] tokens = this.incoming.split("&");
			String sender = tokens[0];//usually a uuid
			String command = "";
			if(tokens.length > 1)
			{
				command = tokens[1]; //REGISTER, PRIVMSG, DELETE, USER
			}
			if(command.equalsIgnoreCase("PRIVMSG") && interrupted==false)//someone is sending a message
			{
			
				String nick = Util.sanitize(tokens[2]);
				String msg = tokens[3];
				device handler = this.theManagment.findDevice(sender);
				if(handler==null)
				{
					hxLog.write("Device Handler Thread", "NullHandler: Nick: " +nick+ " msg: " +msg +"\n");
					//this should not happen as much now because of how devices send updated urls every minute or so
				}
				if(handler!=null)
				{
					//this is much more likely
					if(msg.startsWith("/me"))
					{
						String[] parts = msg.split("/me",2);
						msg = "\u0001ACTION " + parts[1] + "\u0001";
					}
					handler.sendToChannel(msg, nick);
					
					//send that texty goodness to irc
				}
				if(Thread.interrupted())
					this.interrupted = true;
			
			}
			else if(command.equalsIgnoreCase("REGISTER") && interrupted==false)
			{
				//register a new device
				String uuid, location, region, channel, url;
				uuid = tokens[2].trim();;
				location = tokens[3].trim();
				region = tokens[4];
				url = tokens[5].trim();
				channel = "";
				if(tokens.length >6)
				{
					channel = tokens[6].trim();
				}
				this.theManagment.register(uuid, location, region, channel, url,false);
				if(Thread.interrupted())
					this.interrupted = true;
			}
			else if(command.equalsIgnoreCase("USERS") && interrupted==false)
			{
				//the users command is structured like this device&USERS&nick>uuid<nick>uuid
				String users = tokens[2];
				if(users.equalsIgnoreCase("NULL"))
				{
					hxLog.write("Device Handler Thread", "USERS Command returned NULL trying to remove all users\n");
					device theDevice = this.theManagment.findDevice(sender);
					if(theDevice!=null)
					{
						theDevice.quitAllUsers(null);
					}
				}
				else
				{
					String[] usersSeperated = users.split("<",0);
					ArrayList<String> nicks = new ArrayList<String>();
					ArrayList<String> uuids = new ArrayList<String>();
					String nick = "";
					String uuid = "";
					String[] user = null;
					//declare all variables used to seperate the nicks and uuids in a USER command
					for(int i = 0;i<usersSeperated.length;i++)
					{
						user = usersSeperated[i].split(">");
						nick = Util.sanitize(user[0]);
						if(user.length > 1)
						{
							uuid = user[1];
						}
						nicks.add(nick);
						uuids.add(uuid);
					}
					String[] nicksArray = new String[nicks.size()];
					nicks.toArray(nicksArray);
					String[] uuidsArray = new String[uuids.size()];
					uuids.toArray(uuidsArray);
					device theDevice = this.theManagment.findDevice(sender);
					if(theDevice!=null)
					{
						theDevice.updateUsers(nicksArray, uuidsArray);
					}
				}
				if(Thread.interrupted())
					this.interrupted = true;
				
			}

			else if(command.equalsIgnoreCase("DELETE") && interrupted==false)
			{
				String deviceUUID = tokens[2].trim();
				hxLog.write("Device Handler Thread", "Delete Command Received");
				device[] theDevices = this.theManagment.getDevices();
				int deviceIndex = -1;
				for(int i =0; i < theDevices.length;i++)
				{
					if(theDevices[i].getUUID().equals(deviceUUID))
					{
						deviceIndex = i;
						theDevices[i].quitAllUsers("Device Deleted");
						break;
					}
					if(Thread.interrupted())
						this.interrupted = true;
					
				}
				if(deviceIndex!=-1)
				{
					this.theManagment.removeDeviceFromList(deviceIndex);
				}
			}
			else
			{
				hxLog.write("Device Handler Thread", "Unknown command: " +command + "\n");
			}
		}
		Util.getThreads().remove(Thread.currentThread());
		
	}
	

}
